package com.snake.win.screen;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.snake.win.GameWin;
import com.snake.win.web.Client;

import java.util.ArrayList;
import java.util.List;

public class MainMenuScreen extends ScreenAdapter implements Client.MessageListener {

    private final GameWin game;
    private Stage stage;
    private Skin skin;
    private Label statusLabel;
    private Label serverStatusLabel;
    private TextButton startServerButton;
    private TextButton joinGameButton;
    private List<String> receivedMessages = new ArrayList<>();
    private final int MAX_MESSAGES = 5;

    public MainMenuScreen(final GameWin game) {
        this.game = game;
    }

    @Override
    public void show() {
        stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
        Gdx.input.setInputProcessor(stage);

        skin = new Skin();
        skin.add("default-font", game.font, BitmapFont.class);

        TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
        textButtonStyle.font = skin.getFont("default-font");
        textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
        textButtonStyle.down = skin.newDrawable("white", Color.LIGHT_GRAY);
        textButtonStyle.over = skin.newDrawable("white", Color.GRAY);
        skin.add("default", textButtonStyle);

        Label.LabelStyle labelStyle = new Label.LabelStyle(skin.getFont("default-font"), Color.WHITE);
        skin.add("default", labelStyle);

        Table table = new Table();
        table.setFillParent(true);
        table.center();

        Label titleLabel = new Label("Snake Game Online", skin);
        titleLabel.setFontScale(2f);
        table.add(titleLabel).padBottom(50).colspan(2).row();

        startServerButton = new TextButton("Start Server", skin);
        startServerButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if (game.server != null && !game.server.getConnectedClients().isEmpty()) {
                     serverStatusLabel.setText("Server already running/active.");
                } else {
                    game.server.start();
                    serverStatusLabel.setText("Server started on port 12345. Waiting for players...");
                }
            }
        });
        table.add(startServerButton).width(300).height(60).pad(10);

        joinGameButton = new TextButton("Join Game", skin);
        joinGameButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if (game.client != null && !game.client.isConnected()) {
                    statusLabel.setText("Attempting to connect...");
                    game.client.connect(MainMenuScreen.this);
                } else if (game.client != null && game.client.isConnected()) {
                    statusLabel.setText("Already connected. Sending hi...");
                    game.client.sendMessage("Hello from client!");
                } else {
                    statusLabel.setText("Client not initialized.");
                }
            }
        });
        table.add(joinGameButton).width(300).height(60).pad(10).row();
        
        TextButton playButton = new TextButton("Single Player (Offline)", skin);
        playButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                game.setScreen(new GameScreen(game, false, null));
            }
        });
        table.add(playButton).width(300).height(60).padTop(30).colspan(2).row();

        serverStatusLabel = new Label("Server Status: Idle", skin);
        serverStatusLabel.setAlignment(Align.center);
        table.add(serverStatusLabel).padTop(20).colspan(2).row();

        statusLabel = new Label("Client Status: Not Connected", skin);
        statusLabel.setAlignment(Align.center);
        table.add(statusLabel).padTop(10).colspan(2).row();
        
        TextButton startGameOnlineButton = new TextButton("Start Online Game (TEMP)", skin);
        startGameOnlineButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if (game.client != null && game.client.isConnected()) {
                    game.setScreen(new GameScreen(game, true, game.client));
                } else if (game.server != null && !game.server.getConnectedClients().isEmpty()){
                     game.setScreen(new GameScreen(game, true, null));
                }
                else {
                    statusLabel.setText("Client not connected or Server not active!");
                }
            }
        });
        table.add(startGameOnlineButton).width(400).height(60).padTop(20).colspan(2).row();

        stage.addActor(table);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
        stage.draw();

        game.batch.begin();
        float yPos = 100;
        for (int i = receivedMessages.size() - 1; i >= 0; i--) {
            game.font.draw(game.batch, receivedMessages.get(i), 50, yPos);
            yPos += 20;
        }
        game.batch.end();
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void hide() {
        stage.dispose();
    }

    @Override
    public void dispose() {
        if (skin != null) {
            skin.dispose();
        }
    }

    @Override
    public void onMessageReceived(String message) {
        Gdx.app.log("MainMenuScreen", "Message from Server: " + message);
        statusLabel.setText("Server: " + message.substring(0, Math.min(message.length(), 50)) + "...");
        
        receivedMessages.add(message);
        if (receivedMessages.size() > MAX_MESSAGES) {
            receivedMessages.remove(0);
        }

        if ("GAME_START".equals(message)) {
            if (game.client != null && game.client.isConnected()){
                 game.setScreen(new GameScreen(game, true, game.client));
            }
        }
    }

    @Override
    public void onDisconnected() {
        Gdx.app.log("MainMenuScreen", "Disconnected from server.");
        statusLabel.setText("Disconnected from server.");
    }
}
